/*
 * @Descripttion:
 * @version:
 * @Author: cxguo
 * @Date: 2020-04-16 22:20:19
 * @LastEditors: cxguo
 * @LastEditTime: 2020-11-12 16:20:40
 */
import GoodsSelect from '@/views/goods-select'
import { getGoodsTotalPriceByRow } from '@/views/goods-select/mixins/utils.js'
import { getPriceBySkuAndUnit, getDiscountBySkuIds } from '@/api/goods/goods-sku.js'
import store from '@/store'

export default {
  extends: GoodsSelect,
  mixins: [GoodsSelect],
  props: {
    /**
     * 是否开启折扣
     */
    isOpenDiscount: {
      type: Boolean,
      default: true
    }
  },
  created() {
    const originColumnsData = this.originColumnsData
    const qtyCol = originColumnsData.find(item => { return item.field === 'quantity' })
    const priceCol = originColumnsData.find(item => { return item.field === 'price' })
    // 处理qty（显示可用库存）
    this.handleQuantityCol(qtyCol)
    // 处理价格
    this.isOpenDiscount && this.handlePriceCol(priceCol, originColumnsData)
  },
  data() {
    return {
      validRules: {
        skuId: [{ required: true, message: '商品Id必填' }],
        name: [{ required: true, trigger: 'blur', message: '商品名称必填' }],
        code: [{ required: true, message: '商品编号必填' }],
        quantity: [
          { required: true, message: '商品数量必填' },
          { trigger: 'blur', validator: ({ row, cellValue }) => {
            const appData = store.getters.appData
            const { businessSetup } = appData
            const { canUseQty } = row
            return new Promise((resolve, reject) => {
              const isAllowNegStock = businessSetup.isAllowNegStock
              if (isAllowNegStock === '1') {
                if (Number(cellValue) > Number(canUseQty)) {
                  this.$message.success('库存不足，继续销售将导致负库存！')
                }
                return resolve()
              }
              if (Number(cellValue) > Number(canUseQty)) {
                reject(new Error(`库存不足 (可用: ${canUseQty})，您可至“业务设置”开启负库存！`))
              } else {
                resolve()
              }
            })
          } }
        ],
        unitId: [{ required: true, message: '单位必填' }],
        unitMulti: [{ required: true, message: '单位系数必填' }],
        price: [
          { required: true, message: '单价必填' },
          { trigger: 'blur', validator: ({ row, cellValue }) => {
            const appData = store.getters.appData
            const { businessSetup } = appData
            const { priceStr } = row
            const priceObj = JSON.parse(priceStr)
            const minPrice = priceObj['1_2']
            return new Promise((resolve, reject) => {
              const isValiMinSalePrice = businessSetup.isValiMinSalePrice
              if (isValiMinSalePrice !== '1') {
                return resolve()
              }
              if (Number(cellValue) < Number(minPrice)) {
                reject(new Error(`单价低于商品最低售价${minPrice}！`))
              } else {
                resolve()
              }
            })
          } }
        ],
        total: [{ required: true, message: '金额必填' }]
      }
    }
  },
  methods: {
    handleQuantityCol(qtyCol) {
      const editRender = qtyCol.editRender
      if (editRender.props) editRender.props.showCanUseQty = true
      else editRender.props = { showCanUseQty: true }
    },
    handlePriceCol(priceCol, originColumnsData) {
      priceCol.title = '折后单价'
      const discountCols = [
        { field: 'priceDef', title: '单价', width: 100,
          editRender: { name: 'CxInputNumber', props: { size: 'mini', min: 0 }}
        },
        { field: 'discount', title: '折扣(%)', width: 100,
          editRender: { name: 'CxInputNumber', props: { size: 'mini', min: 0 }}
        },
        priceCol
      ]
      const priceColIndex = originColumnsData.findIndex(item => { return item.field === 'price' })
      originColumnsData.splice(priceColIndex, 1, ...discountCols)
    },
    updateTableTotalAmount() {
      const tableData = this.tableData
      tableData.forEach(item => {
        if (item.skuId) {
          const total = getGoodsTotalPriceByRow(item)
          this.$set(item, 'total', total)
          // 税额
          if (this.isOpenTax) {
            const { taxRate } = item
            const taxAmount = this.$amount((taxRate / 100) * total).format()
            this.$set(item, 'taxAmount', taxAmount)
          }
          if (this.isOpenDiscount) {
            let { priceDef, discount } = item
            discount = discount || 0
            priceDef = priceDef || 0
            const price = this.$amount((discount / 100) * priceDef).format()
            this.$set(item, 'price', price)
          }
        }
      })
    },
    handleGoodData(row, rowIndex) {
      let targetData = row
      const { unitIdStr, unitIsbaseStr, skuId } = targetData
      if (unitIdStr && unitIdStr !== '') {
        const baseUnitId = this.getBaseUnitId(unitIdStr, unitIsbaseStr)
        targetData.unitId = baseUnitId
        if (this.isSetPrice) {
          const params = { skuId, unitId: baseUnitId }
          getPriceBySkuAndUnit(params).then(res => {
            if (res.data.flag) {
              const { price } = res.data.data
              if (price) {
                const priceStr = price
                const defaultPrice = this.getBasePrice(price)
                if (this.isOpenDiscount) {
                  this.getDiscountBySkuIds({ skuId }).then(discount => {
                    this.updateTableData(rowIndex, { priceDef: defaultPrice, discount, priceStr })
                  })
                } else {
                  this.updateTableData(rowIndex, { price: defaultPrice, priceStr })
                }
              }
            }
          })
        }
      }
      targetData = this.formatGoodListData([targetData])[0]
      this.updateTableData(rowIndex, targetData)
      this.closeSimpleGoodSelect()
    },
    getDiscountBySkuIds({ skuId }) {
      return new Promise((resolve, reject) => {
        const params = { skuIds: [skuId] }
        getDiscountBySkuIds(params).then(res => {
          if (res.data.flag) {
            const data = res.data.data
            const value = data[0].discount
            const discount = this.$amount(value).format()
            resolve(discount)
          } else {
            reject(new Error(res.data.message))
          }
        })
      })
    }
  }
}
